import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserProfile } from '../models/user-profile.entity';
import { SystemSetting } from '../models/system-setting.entity';
import { ChartData } from '../models/chart-data.entity';

@Injectable()
export class SettingsService {
  constructor(
    @InjectRepository(UserProfile)
    private userProfileRepository: Repository<UserProfile>,
    @InjectRepository(SystemSetting)
    private systemSettingRepository: Repository<SystemSetting>,
    @InjectRepository(ChartData)
    private chartDataRepository: Repository<ChartData>,
  ) {}

  // 用户配置相关方法
  async getUserProfile(): Promise<UserProfile | null> {
    // 假设系统中只有一个用户配置
    return this.userProfileRepository.findOne();
  }

  async updateUserProfile(
    profileData: Partial<UserProfile>,
  ): Promise<UserProfile> {
    let profile = await this.getUserProfile();

    if (!profile) {
      profile = this.userProfileRepository.create(profileData);
    } else {
      this.userProfileRepository.merge(profile, profileData);
    }

    return this.userProfileRepository.save(profile);
  }

  // 系统设置相关方法
  async getSystemSettings(): Promise<SystemSetting | null> {
    // 假设系统中只有一组系统设置
    return this.systemSettingRepository.findOne();
  }

  async updateSystemSettings(
    settingsData: Partial<SystemSetting>,
  ): Promise<SystemSetting> {
    let settings = await this.getSystemSettings();

    if (!settings) {
      settings = this.systemSettingRepository.create(settingsData);
    } else {
      this.systemSettingRepository.merge(settings, settingsData);
    }

    return this.systemSettingRepository.save(settings);
  }

  // 图表数据相关方法
  async getChartData(): Promise<ChartData[]> {
    return this.chartDataRepository.find();
  }
}
